package pl.wroc.uni.ii.gdomo;

import java.util.Date;

import pl.wroc.uni.ii.gdomo.data.DatabaseHelper;
import pl.wroc.uni.ii.gdomo.data.HighScore;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.j256.ormlite.android.AndroidConnectionSource;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class Game extends View {

	private static final int START_LEVEL = -1;
	private static final int MAX_LEVEL = 9;

	private Board board;
	private int screenWidth;
	private int screenHeight;
	private int currentLevel;
	private String hardship;
	private long finishTimeMillis;
	private long startTimeMillis;

	public Game(Context context, String hardship) {
		super(context);
		this.hardship = hardship;
		currentLevel = START_LEVEL;
	}

	public void startNewLevel() {
		currentLevel++;
		if (currentLevel > MAX_LEVEL) {
			finish();
		}
		else if (currentLevel % 2 == 0) {
			board = new PlayBoard(this, currentLevel, screenWidth, screenHeight, hardship);
		}
		else {
			board = new FlashBoard(this,currentLevel);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			int x = (int) event.getX();
			int y = (int) event.getY();
			board.select(x ,y);
			invalidate(); // request onDraw()
		}
		return true;
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		board.draw(canvas);
	}

	private void finish() {
		finishTimeMillis = System.currentTimeMillis();
		try {
			persistScore();
		} catch (Exception e) {
			Log.e(Game.class.getName(), "can't persist score", e);
		}
		Activity puzzle = (Activity) getContext();
		puzzle.finish();
	}

	private void persistScore() throws Exception {
		DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
		
		// you get the SQLiteOpenHelper from your Android Activity
		ConnectionSource connectionSource =
		     new AndroidConnectionSource(databaseHelper);

		Dao<HighScore, Integer> highScoreDao =
		     DaoManager.createDao(connectionSource, HighScore.class);

//		TableUtils.createTable(connectionSource, HighScore.class);

		Long timeSpanMillis = finishTimeMillis - startTimeMillis;
		HighScore highScore = new HighScore(timeSpanMillis, "user", new Date(), hardship);
		
		// persist the account object to the database
		// it should return 1 for the 1 row inserted
		if (highScoreDao.create(highScore) != 1) {
		     throw new Exception("Failure adding highScore");
		}
		connectionSource.close();
	}

	public void start() {
		screenWidth = getMeasuredWidth();
	    screenHeight = getMeasuredHeight();
		startNewLevel();
		startTimeMillis = System.currentTimeMillis();
	}
}
